package com.ruoyi.common.utils;



import cn.hutool.json.JSONUtil;
import com.ruoyi.common.pojo.WeChat;

import java.io.*;
import java.net.*;

public class WeChatLogin {
    public static void main(String[] args) throws IOException {

        String str ="{\"session_key\":\"jodEXMmdyyAy8d6h3+K6bg==\",\"expires_in\":7200,\"openid\":\"otgH60CwMdFH7gQcXrC7GXxodYKU\"}";
        // 使用 Hutool 将 JSON 字符串转换为 Java 对象
        WeChat sessionInfo = JSONUtil.toBean(str, WeChat.class);
        System.out.println("sessionInfo: " + sessionInfo);
        // 填写你自己的AppID和AppSecret
//        String appId = "wx87bd10784fc8639a";
//        String appSecret = "6b5540d92c3c6a183985cec801c38b18";
//        String jsCode = "0d3lWZll2wpa2f4ocDkl2WVRLL0lWZlz";  // 前端传来的jsCode
//
//        // 请求URL，获取access_token和openid
//        String urlStr = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId +
//                        "&secret=" + appSecret + "&js_code=" + jsCode + "&grant_type=authorization_code";
//
//        // 发起HTTP请求
//        String response = sendHttpRequest(urlStr);
//        System.out.println(response);

//        // 解析返回的JSON
//        JSONObject jsonResponse = new JSONObject(response);
//        String accessToken = jsonResponse.getString("access_token");
//        String openid = jsonResponse.getString("openid");
//
//        // 输出openid 和 access_token
//        System.out.println("Access Token: " + accessToken);
//        System.out.println("OpenID: " + openid);
//
//        // 使用 access_token 和 openid 获取用户信息
//        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken +
//                             "&openid=" + openid + "&lang=zh_CN";
//
//        // 获取用户信息
//        String userInfoResponse = sendHttpRequest(userInfoUrl);
//        System.out.println("User Info: " + userInfoResponse);
    }

    private static String sendHttpRequest(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        return response.toString();
    }
}
